package cn.taketoday.live.file;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import cn.taketoday.live.config.GlobalData;
import cn.taketoday.live.utils.FileUtils;
import cn.taketoday.live.utils.JodaTimeUtils;

/**
 * @author BanqiJane
 * @ClassName LogFileTools
 * @Description TODO
 * @date 2020年8月10日 下午12:28:39
 * @Copyright:2020 blogs.acproject.xyz Inc. All rights reserved.
 */
public class LogFileTools {
  private volatile static LogFileTools logFileTools;

  private LogFileTools() {
  }

  public static LogFileTools getlogFileTools() {
    if (logFileTools == null) {
      synchronized(LogFileTools.class) {
        if (logFileTools == null) {
          logFileTools = new LogFileTools();
        }
      }
    }
    return logFileTools;
  }

  public void logFile(String msg) {
    FileWriter fw = null;
    PrintWriter pw = null;
    StringBuilder stringBuilder = new StringBuilder();
    String path = FileUtils.getApplicationPath();
    try {
      // 如果文件存在，则追加内容；如果文件不存在，则创建文件
      path = path + "/Danmuji_log/";
      File file = new File(path);
      file.setWritable(true, false);
      if (file.exists() == false)
        file.mkdirs();
      stringBuilder.append(JodaTimeUtils.getCurrentDateString());
      stringBuilder.append("(");
      stringBuilder.append(GlobalData.ROOM_ID);
      stringBuilder.append(")");
      file = new File(path + stringBuilder.toString() + ".txt");
      file.setWritable(true, false);
      stringBuilder.delete(0, stringBuilder.length());
      if (file.exists() == false)
        try {
          file.createNewFile();
        }
        catch (IOException e) {
          // TODO 自动生成的 catch 块
          e.printStackTrace();
        }
      fw = new FileWriter(file, true);
      pw = new PrintWriter(fw);
      pw.println(msg);
      pw.flush();
      fw.flush();
      pw.close();
      fw.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    finally {
      if (pw != null) {
        pw.close();
      }
      if (fw != null) {
        try {
          fw.close();
        }
        catch (IOException e) {
          // TODO 自动生成的 catch 块
          e.printStackTrace();
        }
      }
    }
  }
}
